package com.santiao.youxiang.ui.activity

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.allen.library.shape.ShapeTextView
import com.santiao.youxiang.bean.EmailBean
import com.gyf.immersionbar.ImmersionBar
import com.santiao.youxiang.MainActivity
import com.santiao.youxiang.R
//import com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
//import kotlin.jvm.java
import com.santiao.youxiang.databinding.ActivityEmailDetailBinding
import com.santiao.youxiang.ext.thrillClickListener
import com.santiao.youxiang.ui.fragment.HomeViewModel
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import com.santiao.youxiang.utils.DemoUtils
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Properties
import javax.mail.Authenticator
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.MessagingException
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

class EamilDetailActivity: AppCompatActivity() {
    private lateinit var binding: ActivityEmailDetailBinding
//    private lateinit var lzyadsUtils: com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
var type_a=0 //1 医保 2：社保
    var type=1 //0新建 1回复

    var slePosition=1
    lateinit var emailBean:EmailBean
//    private val HviewModel: HomeViewModel by viewModels()
    private lateinit var HviewModel: HomeViewModel
    private lateinit var loadingDiaLog: LoadingDiaLog
    var typedel=0  /*0删除 1标记*/

    var struri=""
    // 在类顶部定义
    val REQUEST_STORAGE_PERMISSION = 1001  // 可以是任意唯一整数

    companion object {
        // 定义一个静态方法来创建Intent
        // 定义一个静态方法来创建Intent并携带uri数据
        fun startActivity(context: Context?, bundle: Bundle?) {

//            val intent = Intent(context, EamilDetailActivity::class.java).apply {
//
//
//                putExtra("type", type)
//
//            }
//
//            context!!.startActivity(intent)

            val intent = Intent(context, EamilDetailActivity::class.java)
            if (bundle != null) {
                intent.putExtras(bundle)  // 使用 bundle 传递数据
            }
            context?.startActivity(intent)

        }



    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEmailDetailBinding.inflate(layoutInflater)
        setContentView(binding?.root)
//        type_a= intent.getStringExtra("type").toString()
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()
        initViews(/*type_a*/)
    }



     fun initViews(/*type: String*/) {
//        initad()
         loadingDiaLog=LoadingDiaLog(this@EamilDetailActivity,"发送中...")
         initclick()
         HviewModel= MainActivity.HviewModel

        binding.toolbarBack.setOnClickListener { onBackPressed() }

          emailBean=intent.getSerializableExtra("email") as EmailBean
         type_a=intent.getIntExtra("type",0)

         binding.detailSubject.text=emailBean.subject
         binding.emailFromIcon.text=emailBean.fromName
         binding.emailFromName.text=emailBean.fromName
         binding.emailTime.text= DemoUtils.formatDate(emailBean.time)
         binding.detailTime2.text=DemoUtils.formatDate(emailBean.time)
         binding.detailSend.text=emailBean.fromName+" "+emailBean.fromEmail
         binding.detailGet.text=emailBean.toName

         binding.webView.loadDataWithBaseURL(null, emailBean.content, "text/html", "UTF-8", null)


         // 启用支持缩放功能
         binding.webView.settings.setSupportZoom(true)
         binding.webView.settings.builtInZoomControls = true
         binding.webView.settings.displayZoomControls = false
         binding.webView.settings.loadWithOverviewMode = true
         binding.webView.settings.useWideViewPort = true

    }

    fun initclick(){

        binding.detailDelete.thrillClickListener{
            typedel=0
            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
            if (currentPost!=null) {
                tryToDeleteEmail(currentPost.pAddress, currentPost.pCode,emailBean.uid)
            }
        }

        binding.llJunk.thrillClickListener{
            typedel=1
            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
            if (currentPost!=null) {
                tryToDeleteEmail(currentPost.pAddress, currentPost.pCode,emailBean.uid)
            }
        }
   

        binding.detailReply.thrillClickListener{

//            val bundle=Bundle()
//            bundle.putInt("type",1)
//            bundle.putString("subject",emailBean.subject)
//            bundle.putString("address",emailBean.fromEmail.substringAfter("<").substringBefore(">"))
            replyDialog(emailBean)
//            EmailWriteActivity.
//            LZYBaseActivity.forward<EmailWriteActivity>(this@EmailDetailActivity,bundle)
            
        }
    
        




    }

    private fun replyDialog(emailBeans:EmailBean) {
        val dialog = Dialog(this, R.style.MyDialog)
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.dialog_reply);
//        updateTextColor(dialog)
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )


        dialog.window?.setGravity(Gravity.BOTTOM);
        var tvtitle=dialog.findViewById<TextView>(R.id.tv_title)
        var rcepob=dialog.findViewById<TextView>(R.id.tv_recepit)


        var close=dialog.findViewById<TextView>(R.id.tv_cancel)
        var send=dialog.findViewById<ShapeTextView>(R.id.tv_send)
        var etcontent=dialog.findViewById<EditText>(R.id.et_content)


        rcepob.text=emailBeans.fromEmail.substringAfter("<").substringBefore(">")


        close.thrillClickListener {
            dialog.cancel()
        }

        send.thrillClickListener {

            val currentPost=
                HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
            if (currentPost!=null) {
                sendEmail(currentPost.pAddress,emailBeans.fromEmail.substringAfter("<").substringBefore(">"),
                    emailBeans.subject,etcontent.text.toString(),currentPost.pCode)
            }
        }



        dialog.show()

//        dialog.findViewById<TextView>(R.id.tv_name).setOnClickListener {
//            firstShowDialogTwo(dialog)
//        }
    }


    @OptIn(DelicateCoroutinesApi::class)
    fun tryToDeleteEmail( email: String, authCode: String,uid:Long) {
        var ss=""
        when(typedel){
            0->{
                ss="删除中..."
            }
            1->{
                ss="标记中..."
            }
        }

        val loadingDiaLog= LoadingDiaLog(this@EamilDetailActivity,ss)
        loadingDiaLog.show()
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录
                val folderName=
                    if (HviewModel.currentPostType.value=="126"|| HviewModel.currentPostType.value=="163"){
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿箱"
                            5 -> "垃圾邮件"
                            6 -> "已删除"
                            else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                        }
                    }else if (HviewModel.currentPostType.value=="aliyun") {
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿"
                            5 -> "垃圾邮件"
                            6 -> "已删除邮件"
                            else -> "INBOX"
                        }
                    }else{
                        when(HviewModel.currentEmailType.value) {
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "Sent Messages"
                            4 -> "Drafts"
                            5 -> "Junk"
                            6 -> "Deleted Messages"
                            else -> "INBOX"
                        }
                    }
                val f=store.getFolder(folderName) as IMAPFolder
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${email}" // 是一个邮箱
                store.id(idMap)
                f.open(Folder.READ_WRITE)  // 打开文件夹（只读模式）
                val message=f.getMessageByUID(uid)

//                 获取垃圾邮件文件夹
                val spamFolderName = when {
                    HviewModel.currentPostType.value == "126" ||
                            HviewModel.currentPostType.value == "163" -> "垃圾邮件"

                    HviewModel.currentPostType.value == "aliyun" -> "垃圾邮件"

                    else -> "Junk" // 国际邮箱通常用 Junk
                }

                val spamFolder = store.getFolder(spamFolderName) as IMAPFolder

                when(typedel){
                    0->{
                        message.setFlags(Flags(Flags.Flag.DELETED), true) // 直接删除邮件
                    }
                    1->{
//                        f.copyMessages(arrayOf(message), spamFolder)
//
//                        // 从原始文件夹删除邮件
//                        f.setFlags(arrayOf(message), Flags(Flags.Flag.DELETED), true)
//                        f.expunge()
                        // 将邮件复制到垃圾邮件文件夹
                        f.copyMessages(arrayOf(message), spamFolder)

                        // 从原始文件夹删除邮件
                        f.setFlags(arrayOf(message), Flags(Flags.Flag.DELETED), true)
                        message.setFlags(Flags(Flags.Flag.FLAGGED), true) // 直接标记邮件
                    }
                }


                // 完成操作后关闭文件夹
                f.expunge()
                f.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    if (type_a==1)
                        HviewModel.refreshEmail.value=2
                    else
                        HviewModel.refreshEmail.value=1
                    loadingDiaLog.dismiss()

                    when(typedel){
                        0->{
                            Toast.makeText(this@EamilDetailActivity,"删除邮件成功~", Toast.LENGTH_SHORT).show()
                        }
                        1->{
                            Toast.makeText(this@EamilDetailActivity,"标记成功~", Toast.LENGTH_SHORT).show()
                        }
                    }

//                    Toast.makeText(this@EamilDetailActivity,"删除邮件成功~", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：删除邮件失败")
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    when(typedel){
                        0->{
                            Toast.makeText(this@EamilDetailActivity,"删除邮件失败~", Toast.LENGTH_SHORT).show()
                        }
                        1->{
                            Toast.makeText(this@EamilDetailActivity,"标记失败~", Toast.LENGTH_SHORT).show()
                        }
                    }
//                    Toast.makeText(this@EamilDetailActivity,"删除邮件失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }



    fun   initad() {
//        myContext = requireContext()
//        lzyadsUtils=
//            com.lazyliuzy.commonui.utils.lzy.LZYADSUtils("Task1Activity", this@Task1Activity)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.loadSimpleAd1(com.lazyliuzy.commonui.databinding.ActivityTask1Binding.flAd)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.showAdCpTurn()

    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun sendEmail(from: String, to: String, subject: String, body: String, authCode: String) {
        loadingDiaLog.show()
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? = null
            var smtpHost: String? = null
            val domain = from.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                    smtpHost = "smtp.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                    smtpHost = "smtp.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                    smtpHost = "smtp.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                    smtpHost = "smtp.aliyun.com"
                }
            }
            val properties = Properties()
            properties["mail.smtp.host"] = smtpHost
            properties["mail.smtp.port"] = "465" // SSL
            properties["mail.smtp.auth"] = "true"
            properties["mail.smtp.ssl.enable"] = "true"
            val session = Session.getInstance(properties, object : Authenticator() {
                override fun getPasswordAuthentication(): PasswordAuthentication {
                    return PasswordAuthentication(from, authCode) // 使用授权码
                }
            })
            try {
                val message = MimeMessage(session)
                message.setFrom(InternetAddress(from))
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
                message.subject = subject
                message.setContent( """
                    <html>
                    <head>
                        <style>
                        </style>
                    </head>
                    <body>
                        <p>$body</p>
                    </body>
                    </html>
                """, "TEXT/HTML; charset=UTF-8"
                )
                Transport.send(message)
                val store = session.getStore("imaps")
                store.connect(imapHost, from, authCode)
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${from}" // 是一个邮箱
                store.id(idMap)
                val sentFolder = store.getFolder(if (domain=="qq.com") "Sent Messages" else "已发送")
                if (!sentFolder.exists()) sentFolder.create(Folder.HOLDS_MESSAGES)
                sentFolder.open(Folder.READ_WRITE)
                message.setFlag(Flags.Flag.SEEN, true)
                sentFolder.appendMessages(arrayOf(message))
                sentFolder.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    if (HviewModel.currentEmailType.value==2) {
                        if (type == 1)
                            HviewModel.refreshEmail.value = 2
                        else
                            HviewModel.refreshEmail.value = 1
                    }
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilDetailActivity,"发送邮件成功~", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: MessagingException) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilDetailActivity,"发送邮件失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}